<?php
/**
 * 客户订单
 * (model)
 */

namespace App\Models\CustomerDelivery;

use App\Models\Basics\SysArea;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\Rakuten\RakutenOrder;
use App\Models\SalesReport\FBAInventory;
use App\Models\Sys\Logs;
use App\Util\SerialNo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class CustomerOrder extends Model
{
    protected $table = 'customer_order';

    protected $guarded  = [];

    /**
     * 订单渠道
     * @var string[]
     */
    const ORDER_CHANNEL_CUSTOMER = 1; //C端
    const ORDER_CHANNEL_BUSINESS = 2; //B端
    public static $_shipOrderChannel = [
        self::ORDER_CHANNEL_CUSTOMER => 'C端',
        self::ORDER_CHANNEL_BUSINESS => 'B端',
    ];

    /**
     * 订单类型
     * @var string[]
     */
    const ORDER_TYPE_NORMAL = 1; //普通订单
    const ORDER_TYPE_SEND   = 2; //寄样订单
    public static $_shipOrderType = [
        self::ORDER_TYPE_NORMAL => '普通订单',
        self::ORDER_TYPE_SEND   => '寄样订单',
    ];

    /**
     * erp订单同步状态
     * @var string[]
     */
    const SYNC_NO = 1; //未同步
    const SYNC_YES = 2; //已同步
    const SYNC_ERROR = 3; //同步异常
    public static $_erpSync = [
        1 => '未同步',
        2 => '已同步',
        3 => '同步异常',
    ];

    /**
     * 是否为自建订单
     */
    const CREATE_NO  = 0;   //自动生成订单(否)
    const CREATE_YES = 1;   //真实自建订单(是)

    /**
     * 关联订单详情
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function detail(){
        return $this->hasMany(CustomerOrderDetails::class, 'order_no', 'order_no');
    }

    /**
     * 关联订单地址
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function receiver(){
        return $this->hasOne(CustomerOrderReceiver::class, 'order_no', 'order_no');
    }

    /**
     * 关联站点
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area(){
        return $this->belongsTo(SysArea::class, 'area_id');
    }

    /**
     * 关联平台国家
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function country(){
        return $this->belongsTo(SysPlatCountry::class, 'country_id');
    }

    public static function countryCode($country){
        $countryCast = [
            'United States' => 'US',
            'Japan' => 'JP',
            'Canada' => 'CA',
            'United Kingdom' => 'UK',
        ];
        $_country = ucwords($country);
        return array_key_exists($_country,$countryCast) ? $countryCast[$_country] : $country;
    }

    protected static function boot()
    {
        parent::boot();

        static::deleting(function($order) {
            $order->detail()->delete();
            $order->receiver()->delete();
        });
    }

    public static $_class = [
        'detail' => CustomerOrderDetails::class ,
        'order' => self::class
    ];

    public static function extractStatus($status){
        if(max($status) == 1 || min($status) == 4)return 1;
        return 2;
    }

    /**
     * 获取站外站点ID
     * @return int
     */
    public static function getSysAreaOutId(){
        return SysArea::getSysOutAreaIdByArea();
    }

    /**
     * 创建erp客户订单 (乐天平台)
     * @param $rakutenOrders
     * @return bool
     */
    public static function addRakutenCustomerOrder($rakutenOrders){
        if (!$rakutenOrders) return false;

        $customerOrderFlag = false;
        $platId = SysPlat::PLAT_RAKUTEN;

        DB::beginTransaction();
        try{
            foreach($rakutenOrders as $rakutenOrder){
                //验证：客户消费订单
                $customerOrderObj = CustomerOrder::query()->where('order_no', $rakutenOrder->order_id)->first();
                if($customerOrderObj){
                    $customerOrderFlag = true;
                    continue;
                }

                $countryCode = $rakutenOrder->rakuten_orders_address->country ?? ''; //国家编码('JP')
                if (!$countryCode) continue;
                $countryId = SysPlatCountry::getCountryId($countryCode); //国家id
                if (!$countryId) continue;
                $areaId = SysPlatCountry::getAreaIdByCountryId($countryId); //站点id
                if (!$areaId) continue;

                //1.客户订单
                $orderDatetime = $rakutenOrder->order_datetime + 3600; //(下单时间加1小时，对应日本时区)
                $customerOrder = [
                    'order_no'      => $rakutenOrder->order_id,
                    'order_at'      => date('Y-m-d H:i:s', $orderDatetime), //下单时间
                    'order_channel' => CustomerOrder::ORDER_CHANNEL_CUSTOMER, //订单渠道 (1.C端，2.B端)
                    'order_type'    => CustomerOrder::ORDER_TYPE_NORMAL, //订单类型 (1.普通订单，2.寄样订单)
                    'plat_id'       => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                    'area_id'       => $areaId,
                    'country_id'    => $countryId,
                    'country_code'  => $countryCode,
                    //'sync_status'       => CustomerOrder::SYNC_NO, //未同步
                    //'overseas_order_id' => $rakutenOrder->overseas_order_id ?? '', //海外仓单号
                ];

                //2.客户订单明细
                $customerOrderDetail = [];
                if ($rakutenOrder->rakuten_orders_items) {
                    foreach($rakutenOrder->rakuten_orders_items as $rakutenOrderItem){
                        $customerOrderDetail[] = [
                            'plat_id'   => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                            'psku_id'   => $rakutenOrderItem->psku_id,
                            'plat_sku'  => $rakutenOrderItem->platform_sku,
                            'order_num' => $rakutenOrderItem->units,
                            'apply_num' => 0,
                            'status' => CustomerOrderDetails::ORDER_DELIVERY_NO, //未申请发货
                            //'sync_status' => CustomerOrder::SYNC_NO, //未同步
                            //'overseas_order_id' => $rakutenOrder->overseas_order_id ?? '', //海外仓单号
                        ];
                    }
                }
                if (count($customerOrderDetail) != count($rakutenOrder->rakuten_orders_items)){
                    $customerOrderFlag = false;
                    break;
                }
                //当多个sku相同时,合并累加相同sku的下单数量
                $orderDetail = [];
                foreach ($customerOrderDetail as $k => $v){
                    if (!isset($orderDetail[$v['plat_sku']])){
                        $orderDetail[$v['plat_sku']]= $v ;
                    } else {
                        $orderDetail[$v['plat_sku']]['units'] += $v['units'];
                    }
                }

                //3.客户订单地址
                $customerOrderReceiver = [
                    'country'   => $rakutenOrder->rakuten_orders_address->country ?? '',
                    'receiver'  => $rakutenOrder->rakuten_orders_address->family_name ?? '',
                    'state'     => $rakutenOrder->rakuten_orders_address->prefecture ?? '',
                    'city'      => $rakutenOrder->rakuten_orders_address->city ?? '',
                    'address'   => $rakutenOrder->rakuten_orders_address->address ?? '',
                    'postcode'  => $rakutenOrder->rakuten_orders_address->zip_code ?? '',
                    'phone'     => $rakutenOrder->rakuten_orders_address->phone_number ?? '',
                ];

                //创建erp客户订单
                $customerOrderObj = CustomerOrder::query()->create($customerOrder);
                $customerOrderObj->detail()->createMany($orderDetail);
                $customerOrderObj->receiver()->create($customerOrderReceiver);

                //更新乐天订单
                $rakutenOrder->erp_sync = RakutenOrder::SYNC_YES;//同步正常
                $rakutenOrder->save();
                if ($rakutenOrder->rakuten_orders_items) {
                    foreach($rakutenOrder->rakuten_orders_items as $item){
                        $item->erp_sync = RakutenOrder::SYNC_YES;//已同步
                        $item->save();
                    }
                }

                $customerOrderFlag = true;
            }

            DB::commit();
            return $customerOrderFlag;
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 创建erp客户发货单 (第三方平台)
     * @param $rakutenOrder
     * @param int $deliveryType
     * @param int $accountId
     * @return bool
     */
    public static function addCustomerDelivery($rakutenOrder,$deliveryType = 2,$accountId = 200000){

        $deliveryFlag = false;
        $customerOrderObj = CustomerOrder::query()->where('order_no',$rakutenOrder->order_id)->first();
        if(!$customerOrderObj) return $deliveryFlag; //客户消费订单

        //FBA仓、海外仓
        $deliveryStatus = CustomerDeliveryDetail::STATUS_DELIVERY_NO; // 3:待发货（默认发货状态）
        //国内仓
        if ($deliveryType == 3){
            $deliveryStatus = CustomerDeliveryDetail::STATUS_READY_NO; // 1:待备货（国内默认状态）
        }

        //验证实际发货单号(批次)
        $_deliveryOrderNo = CustomerDeliveryDetail::query()
            ->where('order_no', $customerOrderObj->order_no)
            ->orderBy('id', 'DESC')
            ->limit(1)
            ->value('delivery_order_no');
        $deliveryOrderNo = formatStrOrderNo($_deliveryOrderNo) ?? $customerOrderObj->order_no;

        //组装客户订单发货明细数据
        $deliveryDetail = [];
        foreach ($customerOrderObj->detail as $key => $item){
            if($item->status == CustomerOrderDetails::ORDER_DELIVERY_CANCEL) continue;

            $warehouseId = 0;
            if ($deliveryType == 2) {
                $warehouseId = 69; //日本谷仓ID
            }

            //获取(FBA)发货站点下的账号以及sku可用库存
            $sellerSku = '';
            if ($deliveryType == 1) {
                $FBAareaInventory = FBAInventory::getFBAInventoryRakuten($customerOrderObj->area_id, $item->psku_id, $accountId);
                $sellerSku = $FBAareaInventory->seller_sku ?? ''; //amazon平台sku
                $accountId = $FBAareaInventory->account_id ?? 0; //amazon平台账号
            }

            $deliveryDetail[] = [
                'order_no'          => $customerOrderObj->order_no, //订单号
                'delivery_order_no' => $deliveryOrderNo, //实际发货订单号
                'order_detail_id'   => $item->id, //订单明细id
                'psku_id'           => $item->psku_id ?? 0,
                'seller_sku'        => $sellerSku,
                'plat_id'           => $customerOrderObj->plat_id ?? 0,
                'plat_sku'          => $item->plat_sku ?? '',
                'apply_num'         => $item->order_num ?? 0,
                'ship_num'          => 0,
                'account_id'        => $accountId,
                'warehouse_id'      => $warehouseId, //海外仓默认,日本谷仓ID
                'apply_remarks'     => '',
                'delivery_type'     => $deliveryType,
                'delivered_at'      => $customerOrderObj->order_at ?? date('Y-m-d H:i:s', time()),
                'status'            => $deliveryStatus
            ];
        }
        if(count($deliveryDetail) == 0) return false;

        //DB::beginTransaction();
        //try{
            //创建发货单
            $deliveryNo = SerialNo::getOOSNo();
            $delivery = CustomerDelivery::query()->create([
                'delivery_no'   => $deliveryNo,
                'order_no'      => $customerOrderObj->order_no,
                'order_at'      => $customerOrderObj->order_at,
                'plat_id'       => $customerOrderObj->plat_id,
                'area_id'       => $customerOrderObj->area_id,
                'country_id'    => $customerOrderObj->country_id,
                'seller_id'     => 124, //日本站销售ID
                'delivery_type' => $deliveryType,
                'delivered_at'  => $customerOrderObj->order_at ?? date('Y-m-d H:i:s', time()),
                'status'        => $deliveryStatus
            ]);
            //创建发货明细
            $delivery->detail()->createMany($deliveryDetail);
            //创建发货地址
            $delivery->receiver()->create([
                'order_no'   => $customerOrderObj->order_no,
                'country'    => $customerOrderObj->receiver->country ?? '',
                'receiver'   => $customerOrderObj->receiver->receiver ?? '',
                'address'    => $customerOrderObj->receiver->address ?? '',
                'state'      => $customerOrderObj->receiver->state ?? '',
                'city'       => $customerOrderObj->receiver->city ?? '',
                'postcode'   => $customerOrderObj->receiver->postcode ?? '',
                'phone'      => $customerOrderObj->receiver->phone ?? ''
            ]);
            if (!$delivery) return false;

            //发货单日志
            $adminId = 1; //操作人ID
            $logType = Logs::CUSTOMER_ORDER_FBA; //FBA
            if ($deliveryType == 2) $logType = Logs::CUSTOMER_ORDER_ABROAD; //海外仓
            if ($deliveryType == 3) $logType = Logs::CUSTOMER_ORDER_CN; //国内
            Logs::logs($logType,"创建发货单：{$deliveryNo}", $delivery->id, $adminId);

            //更新客户订单明细状态
            $customerOrderObj->sync_status = CustomerOrder::SYNC_YES; //发货单已同步
            $customerOrderObj->save();
            if ($customerOrderObj->detail) {
                foreach ($customerOrderObj->detail as $key => $item){
                    $orderDetailStatus = CustomerOrderDetails::getOrderDetailStatus($item, $item->order_num); //申请发货数量(与订单数量保持一致)
                    $item->status = $orderDetailStatus; //申请状态 (1:未申请 2:部分申请 3:完全申请 4:已取消)
                    $item->sync_status = CustomerOrder::SYNC_YES; //发货单已同步
                    $item->save();
                }
            }

            $deliveryFlag = true;
            return $deliveryFlag;

        //    DB::commit();
        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //}
    }

}
